//
//  PayViewController.m
//  MZJ
//
//  Created by XDD on 16/6/25.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "PayViewController.h"
#import "Pay_View.h"

@interface PayViewController ()<BeeCloudDelegate> {
    BCPayReq *payReq_;
    NSString *bsn_Str;
    

}

@property (nonatomic, strong)Pay_View *payView;
@property (nonatomic, strong)NSString *choose_payType_Str;
@property (nonatomic, strong)UITextField *contribute_Money_TextField;
@property (nonatomic, strong) NetWorkingSModel *model;

@end

@implementation PayViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    [BeeCloud initWeChatPay:@"wxf817de90a75156e5"];

}

- (void)viewDidDisappear:(BOOL)animated {

    [super viewDidDisappear:animated];
    
    [DataModel object].care_ID_Str = nil;
    [DataModel object].Query_ID_Str = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.topBar.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    self.titleLabel.text = @"我要捐款";
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.backButton setTitle:@"" forState:UIControlStateNormal];
    
    [BeeCloud setBeeCloudDelegate:self];

    UIView *projectView = [[UIView alloc]initWithFrame:CGRectMake(1, 70, kWidth - 2, 35)];
    projectView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:projectView];
    
    UILabel *projectName = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 90, 25)];
    projectName.text = @"捐赠项目";
    projectName.font = [UIFont systemFontOfSize:15];
    projectName.textAlignment = NSTextAlignmentCenter;
    [projectView addSubview:projectName];
    
    UILabel *projectName_Data = [[UILabel alloc]initWithFrame:CGRectMake(110, 5, kWidth - 120, 25)];
    projectName_Data.text = [DataModel object].property_Str;
    projectName_Data.textColor = [UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:1];
    projectName_Data.font = [UIFont systemFontOfSize:15];
    projectName_Data.textAlignment = NSTextAlignmentLeft;
    [projectView addSubview:projectName_Data];
    
    UIView *contributeView = [[UIView alloc]initWithFrame:CGRectMake(1, 115, kWidth - 2, 71)];
    contributeView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:contributeView];
    
    UILabel *contributeName = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 90, 25)];
    contributeName.text = @"捐  赠  人";
    contributeName.font = [UIFont systemFontOfSize:15];
    contributeName.textAlignment = NSTextAlignmentCenter;
    [contributeView addSubview:contributeName];
    
    UILabel *contributeName_Data = [[UILabel alloc]initWithFrame:CGRectMake(110, 5, kWidth - 120, 25)];
    contributeName_Data.text = [DataModel object].userDetail[@"unickname"];
    contributeName_Data.textColor = [UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:1];
    contributeName_Data.font = [UIFont systemFontOfSize:15];
    contributeName_Data.textAlignment = NSTextAlignmentLeft;
    [contributeView addSubview:contributeName_Data];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 35, contributeView.frame.size.width, 1.5f)];
    lineView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [contributeView addSubview:lineView];
    
    UILabel *contributeName_PhoneNum = [[UILabel alloc]initWithFrame:CGRectMake(0, 41, 90, 25)];
    contributeName_PhoneNum.text = @"联系电话";
    contributeName_PhoneNum.font = [UIFont systemFontOfSize:15];
    contributeName_PhoneNum.textAlignment = NSTextAlignmentCenter;
    [contributeView addSubview:contributeName_PhoneNum];
    
    UILabel *contributeName_PhoneNum_Data = [[UILabel alloc]initWithFrame:CGRectMake(110, 41, kWidth - 120, 25)];
    contributeName_PhoneNum_Data.text = [DataModel object].userDetail[@"umobile"];
    contributeName_PhoneNum_Data.textColor = [UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:1];
    contributeName_PhoneNum_Data.font = [UIFont systemFontOfSize:15];
    contributeName_PhoneNum_Data.textAlignment = NSTextAlignmentLeft;
    [contributeView addSubview:contributeName_PhoneNum_Data];
    
    UIView *moneyView = [[UIView alloc]initWithFrame:CGRectMake(1, 196, kWidth - 2, 35)];
    moneyView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:moneyView];
    
    UILabel *contribute_Money = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 90, 25)];
    contribute_Money.text = @"捐赠金额";
    contribute_Money.font = [UIFont systemFontOfSize:15];
    contribute_Money.textAlignment = NSTextAlignmentCenter;
    [moneyView addSubview:contribute_Money];
    
    UIView *moneyView_Data = [[UIView alloc]initWithFrame:CGRectMake(110, 5, kWidth - 200, 25)];
    moneyView_Data.backgroundColor = [UIColor whiteColor];
    moneyView_Data.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    moneyView_Data.layer.cornerRadius = 2.0;
    moneyView_Data.layer.borderWidth = 1.0;
    moneyView_Data.layer.masksToBounds = YES;
    [moneyView addSubview:moneyView_Data];
    
    _contribute_Money_TextField = [[UITextField alloc]initWithFrame:CGRectMake(5, 1, moneyView_Data.frame.size.width - 10, 23)];
    _contribute_Money_TextField.placeholder = @"输入金额";
    _contribute_Money_TextField.font = [UIFont systemFontOfSize:12];
    [moneyView_Data addSubview:_contribute_Money_TextField];
    
    UIButton *pay_Button = [UIButton buttonWithType:UIButtonTypeCustom];
    pay_Button.frame = CGRectMake(70, 300, kWidth - 140, 35);
    [pay_Button setTitle:@"前往支付" forState:UIControlStateNormal];
    [pay_Button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    pay_Button.titleLabel.font = [UIFont systemFontOfSize:16];
    pay_Button.backgroundColor = [UIColor colorWithRed:43/255.0 green:131/255.0 blue:210/255.0 alpha:1];
    pay_Button.layer.cornerRadius = 3.0;
    pay_Button.layer.masksToBounds = YES;
    [pay_Button addTarget:self action:@selector(pay_ButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:pay_Button];
    
    _choose_payType_Str = @"WX";
}

- (void)pay_ButtonAction {
    
    [_contribute_Money_TextField resignFirstResponder];
    if ([_contribute_Money_TextField.text intValue] < 1) {
        [self waringAction:@"输入金额需大于1(单位：元)"];
    }else {
        if (!_model) {
            _model = [[NetWorkingSModel alloc]init];
        }
        __weak typeof (self)weakSelf = self;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *token = [user objectForKey:@"user_token"];
        if (token.length != 0) {
            
            [dic setObject:token forKey:@"token"];
            if ([self.panduan_Str isEqualToString:@"care_Str"]) {
                [dic setObject:[DataModel object].care_ID_Str forKey:@"acid"];
            }
            if ([self.panduan_Str isEqualToString:@"query_Str"]) {
                [dic setObject:[DataModel object].Query_ID_Str forKey:@"pid"];
            }
            
            [dic setObject:[NSString stringWithFormat:@"%f",[_contribute_Money_TextField.text floatValue]*100] forKey:@"price"];
        }
        [_model setBlockWithReturnBlock:^(id returnValue) {
            if ([returnValue[@"statu"] integerValue] != 0) {
                [weakSelf waringAction:returnValue[@"result"]];
            }
            else {
                bsn_Str = returnValue[@"result"][@"bsn"];
                weakSelf.payView.hidden = NO;
                weakSelf.payView.mBview_pay.hidden = NO;
                [UIView animateWithDuration:0.35 animations:^{
                    weakSelf.payView.paytype_View.frame = CGRectMake(60, kHeight/3 - 20, kWidth - 120 , 260);
                }];
            }
            NSLog(@"支付申请 = %@",returnValue);
        } WithErrorBlock:^(id errorCode) {
            
        }];
        [weakSelf.model PayappGetpay_ask:dic];
    }
}

- (Pay_View *)payView {
    if (!_payView) {
        _payView = [[Pay_View alloc]initWithFrame:self.view.frame];
        [self.view addSubview:_payView];
        
        __weak typeof (self)weakSelf = self;
        [_payView setDidsingleTapClickActionBlock:^{
            weakSelf.payView.mBview_pay.hidden = YES;
            [UIView animateWithDuration:0.35 animations:^{
                weakSelf.payView.paytype_View.frame = CGRectMake(60, kHeight/3 - 20, kWidth - 120, 0);
            }];
            weakSelf.payView.hidden = YES;
        }];
        [_payView setDidquxiaoBtnActionBlock:^{
            weakSelf.payView.mBview_pay.hidden = YES;
            [UIView animateWithDuration:0.35 animations:^{
                weakSelf.payView.paytype_View.frame = CGRectMake(60, kHeight/3 - 20, kWidth - 120, 0);
            }];
            weakSelf.payView.hidden = YES;
        }];
        [_payView setDidpay_BtnActionBlock:^{
            if ([weakSelf.choose_payType_Str isEqualToString:@"WX"]) {
                [weakSelf doWXAppPay];
            }
            if ([weakSelf.choose_payType_Str isEqualToString:@"ZFB"]) {
                [weakSelf doAliAppPay];
            }
            if ([weakSelf.choose_payType_Str isEqualToString:@"YL"]) {
                [weakSelf doUnionPay];
            }
            
        }];
        [_payView setDidwx_ButtonActionBlock:^{
            weakSelf.payView.wx_ImageView_choose.image = [UIImage imageNamed:@"iconfont-gouxuan_img"];
            weakSelf.payView.zfb_ImageView_choose.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.payView.yl_ImageView_choose.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.choose_payType_Str = @"WX";

        }];
        [_payView setDidzfb_ButtonActionBlock:^{
            weakSelf.payView.wx_ImageView_choose.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.payView.zfb_ImageView_choose.image = [UIImage imageNamed:@"iconfont-gouxuan_img"];
            weakSelf.payView.yl_ImageView_choose.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.choose_payType_Str = @"ZFB";


        }];
        [_payView setDidyl_ButtonActionBlock:^{
            weakSelf.payView.wx_ImageView_choose.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.payView.zfb_ImageView_choose.image = [UIImage imageNamed:@"Checked-NO_img@2x"];
            weakSelf.payView.yl_ImageView_choose.image = [UIImage imageNamed:@"iconfont-gouxuan_img"];
            weakSelf.choose_payType_Str = @"YL";


        }];
    }
    return _payView;
}
//点击返回键
- (void)clickedBackButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - BeeCloud delegate

- (void)onBeeCloudResp:(BCBaseResp *)resp {
    switch (resp.type) {
        case BCObjsTypePayResp:
        {
            BCPayResp *tempResp = (BCPayResp *)resp;
            if (tempResp.resultCode == 0) {
                //                                BCPayReq *payReq = (BCPayReq *)resp.request;
                //微信、支付宝、银联支付结果
                //                [self showAlertView:resp.resultMsg];
                
//                [self chongzhichenggong];
                
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
                
            }
        }
            break;
        case BCObjsTypeQueryResp:{
            
        }
            break;
        case BCObjsTypeOfflineBillStatusResp:{
            
        }
            break;
        case BCObjsTypeOfflineRevertResp:{
            
        }
            break;
        default:{
            
        }
            break;
    }
}

//支付宝
- (void)doPay:(PayChannel)channel {
    //    NSString *billno = [self genBillNo];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value",@"key", nil];
    
    payReq_ = [[BCPayReq alloc] init];
    payReq_.channel = channel;
    payReq_.title = @"民政局捐款详情";//订单详情
    payReq_.totalFee = [NSString stringWithFormat:@"%.f",[_contribute_Money_TextField.text floatValue]*100];//支付金额
    //    payReq_.totalFee  = @"1";
    payReq_.billNo = bsn_Str;//订单号
    payReq_.scheme = @"MZJPay";
    payReq_.billTimeOut = 300;
    payReq_.viewController = self;
    payReq_.optional = dict;
    [BeeCloud sendBCReq:payReq_];
    
//    payView.hidden = YES;
//    Mbview.hidden = YES;
    
//    [self endHud];
}

- (void)showAlertView:(NSString *)msg {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定"
                                                        style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction *action) {
                                                          //                                                          ViewController *myOrderVC = [[ViewController alloc]init];
                                                          //                                                          [self.navigationController pushViewController:myOrderVC animated:YES];
                                                      }]];
    [self presentViewController:alertController
                       animated:YES
                     completion:nil];
}

//- (void)chongzhichenggong  {
//    //    payView.hidden = YES;
//    //    Mbview.hidden = YES;
//    
//    UIView *Mbview1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, screenWith, screenHeight)];
//    Mbview1.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.6];
//    //    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapClickAction:)];
//    [self.view addSubview:Mbview1];
//    //    [Mbview1 addGestureRecognizer:singleTap];
//    
//    UIImageView *chongzhichenggongImageView = [[UIImageView alloc]initWithFrame:CGRectMake(30, screenHeight/3, screenWith - 60, screenHeight/3 + 60)];
//    chongzhichenggongImageView.image = [UIImage imageNamed:@"chongzhichenggong_img@2x"];
//    chongzhichenggongImageView.userInteractionEnabled = YES;
//    [Mbview1 addSubview:chongzhichenggongImageView];
//    
//    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    button.frame = CGRectMake(40, chongzhichenggongImageView.frame.size.height - 60, chongzhichenggongImageView.frame.size.width - 80, 36);
//    [button setTitle:@"点击开始游玩预约" forState:UIControlStateNormal];
//    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    button.backgroundColor = [UIColor colorWithRed:81/255.0 green:159/255.0 blue:39/255.0 alpha:1];
//    button.layer.cornerRadius = 18.0;
//    button.layer.masksToBounds = YES;
//    button.titleLabel.font = [UIFont systemFontOfSize:14];
//    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//    [chongzhichenggongImageView addSubview:button];
//}

//- (IBAction)buttonAction:(id)sender {
//    self.tabBarController.tabBar.hidden = NO;
//    self.tabBarController.selectedIndex = 1;
//    [self.navigationController popViewControllerAnimated:YES];
//}

#pragma mark - 生成订单号
- (NSString *)genBillNo {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    return [formatter stringFromDate:[NSDate date]];
}

#pragma mark - 支付宝
- (void)doAliAppPay {
    [self doPay:PayChannelAliApp];
    
}

#pragma mark - 微信支付
- (void)doWXAppPay {
    [self doPay:PayChannelWxApp];
}

#pragma mark - 银联在线
- (void)doUnionPay {
    [self doPay:PayChannelUnApp];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
